// pages/admin/notice-manage/notice-manage.js
const { get, post, put, del } = require('../../../utils/request')
const { formatDate, showSuccess, showError, showConfirm } = require('../../../utils/util')

Page({
  data: {
    noticeList: [],
    loading: false,

    // 弹窗相关
    showModal: false,
    isEdit: false,
    formData: {
      title: '',
      content: ''
    },
    submitting: false
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadNoticeList()
  },

  onShow() {
    this.loadNoticeList()
  },

  onPullDownRefresh() {
    this.loadNoticeList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载公告列表
  loadNoticeList(callback) {
    this.setData({ loading: true })

    get('/notice/selectAll').then(res => {
      const noticeList = res.data || []

      // 格式化时间
      noticeList.forEach(item => {
        if (item.time) {
          item.time = formatDate(item.time)
        }
      })

      this.setData({
        noticeList
      })
    }).catch(err => {
      showError('加载公告列表失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 添加公告
  addNotice() {
    this.setData({
      showModal: true,
      isEdit: false,
      formData: {
        title: '',
        content: ''
      }
    })
  },

  // 编辑公告
  editNotice(e) {
    const notice = e.currentTarget.dataset.notice

    this.setData({
      showModal: true,
      isEdit: true,
      formData: {
        id: notice.id,
        title: notice.title,
        content: notice.content
      }
    })
  },

  // 删除公告
  async deleteNotice(e) {
    const { id, title } = e.currentTarget.dataset

    try {
      await showConfirm(`确定要删除公告"${title}"吗？此操作不可恢复。`)
    } catch {
      return
    }

    del(`/notice/delete/${id}`).then(res => {
      showSuccess('删除成功')
      this.loadNoticeList()
    }).catch(err => {
      showError(err.msg || '删除失败')
    })
  },

  // 表单输入事件
  onTitleInput(e) {
    this.setData({
      'formData.title': e.detail.value
    })
  },

  onContentInput(e) {
    this.setData({
      'formData.content': e.detail.value
    })
  },

  // 关闭弹窗
  closeModal() {
    this.setData({
      showModal: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止点击弹窗内容时关闭弹窗
  },

  // 表单验证
  validateForm() {
    const { title, content } = this.data.formData

    if (!title.trim()) {
      showError('请输入公告标题')
      return false
    }

    if (!content.trim()) {
      showError('请输入公告内容')
      return false
    }

    if (title.trim().length < 2) {
      showError('公告标题至少需要2个字符')
      return false
    }

    if (content.trim().length < 5) {
      showError('公告内容至少需要5个字符')
      return false
    }

    return true
  },

  // 保存公告
  async saveNotice() {
    if (this.data.submitting) return

    if (!this.validateForm()) return

    this.setData({ submitting: true })

    const submitData = {
      title: this.data.formData.title.trim(),
      content: this.data.formData.content.trim(),
      time: new Date().toISOString()
    }

    try {
      if (this.data.isEdit) {
        submitData.id = this.data.formData.id
        await put('/notice/update', submitData)
        showSuccess('修改成功')
      } else {
        await post('/notice/add', submitData)
        showSuccess('发布成功')
      }

      this.closeModal()
      this.loadNoticeList()

    } catch (err) {
      showError(err.message || '保存失败，请重试')
    } finally {
      this.setData({ submitting: false })
    }
  }
})
